//
//  JPStatusViewModel.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/23.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit
import YYText

class JPStatusViewModel: NSObject {
    
    //  微博模型对象
    var status: JPStatusModel?
    //  提供会员等级图片
    var mbrankImage: UIImage?
    //  转发数
    var retweetCountContent: String?
    //  评论数
    var commentCountContent: String?
    //  赞
    var unlikeCountContent: String?
    //  转发微博内容
    var retweetContent: String?
    //  微博来源
    var sourceString: String?
    //  认证类型的图片
    var verifiedTypeImage: UIImage?
    //  微博时间
    var timeContent: String? {
        guard let creatTime = status?.created_at else {
            return nil
        }
        
        return Date.creatDate(dateStr: creatTime).sinceDateFromNow
    }
    //  原创微博富文本
    var originalAttributeString: NSAttributedString?
    //  转发微博富文本
    var retweetAttributeString: NSAttributedString?
    
    
    
    
    
    init(status: JPStatusModel) {
        super.init()
        self.status = status
        
        //处理业务逻辑
        handleMbrankImage(mbrank: status.user?.mbrank ?? 0)
        
        retweetCountContent = handleCountContent(count: status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCountContent(count: status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCountContent(count: status.attitudes_count, defaultTitle: "赞")
        handleSourceContent(sourceStr: status.source!)
        handleVerifiedTypeImage(verifiedType: status.user?.verified_type ?? 0)
        handleRetweetContent(status: status)
        originalAttributeString = handleStatusAttributeString(text: status.text! ,isRetweet: false)
        
        print("~~~~~~~~")
        print("~~~~~~~~")
        print("~~~~~~~~")
        print("~~~~~~~~")
        print(originalAttributeString);
        
        
    }
    
    //  处理微博富文本
    private func handleStatusAttributeString(text: String ,isRetweet: Bool) -> NSMutableAttributedString? {
        print(text)
        let attributeStringM = NSMutableAttributedString(string: text)
        
        let matchResults = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        
        for result in matchResults.reversed() {
            let chs = (text as NSString).substring(with: result.range)
            
            if let emotion = JPEmotionTool.sharedEmotionTool.seacherEmotionWithChs(chs: chs)  {
                
                let image = UIImage (named: emotion.path!)
                
                let attributedStr = NSAttributedString.yy_attachmentString(withEmojiImage: image!, fontSize: 14)
                
//                if emotion.type == "0" {
//                    let attributedStr = NSAttributedString.attributedStringWithFont(font: UIFont.systemFont(ofSize: 14), emotion: emotion)
                    attributeStringM.replaceCharacters(in: result.range, with: attributedStr!)
//                }else {
//                    
//                }
            }
        
        }
        
        attributeStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, attributeStringM.length))
        
        if isRetweet {
            //  转发富文本颜色
            attributeStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, attributeStringM.length))
        } else {
            //  原创富文本颜色
            //  设置富文本的字体颜色
            attributeStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, attributeStringM.length))
            
        }
        
        
        addHighlightedContent(regular: "@\\w+", attributeStringM: attributeStringM)
        addHighlightedContent(regular: "#[^#]+#", attributeStringM: attributeStringM)
        addHighlightedContent(regular: "http[s]?://[^\\s\\u4e00-\\u9fa5]+", attributeStringM: attributeStringM)
        return attributeStringM
        
    }
    
    //  处理微博高亮显示内容
    private func addHighlightedContent(regular: String, attributeStringM: NSMutableAttributedString) {
        let text = attributeStringM.string
        
        let matchResult = try! NSRegularExpression(pattern: regular, options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        
        for match in matchResult {
            
            
            let color = UIColor(red: 80 / 255, green: 125 / 255, blue: 215 / 255, alpha: 1)
            attributeStringM.addAttribute(NSForegroundColorAttributeName, value: color, range: match.range)
            
            let borderColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
            let border = YYTextBorder(fill: borderColor, cornerRadius: 3)
            border.insets = UIEdgeInsetsMake(1, 0, -1, 0)
            
            let highlightedText = YYTextHighlight()
            highlightedText.setBackgroundBorder(border)
            
            attributeStringM.yy_setTextHighlight(highlightedText, range: match.range)
            
        }
        
        return
    }
    
    //  处理微博来源
    private func handleSourceContent(sourceStr: String) {
        
        //<a href="http://app.weibo.com/t/feed/6vtZb0" rel="nofollow">微博 weibo.com</a>
        if sourceStr.contains("\">") && sourceStr.contains("</") {
            let startRange = sourceStr.range(of: "\">")
            let endRange = sourceStr.range(of: "</")
            let startIndex = startRange?.upperBound
            let endIndex = endRange?.lowerBound
            
            sourceString = sourceStr.substring(with: startIndex!..<endIndex!)
        }
    }
    
    //处理会员等级逻辑
    private func handleMbrankImage(mbrank: Int) {
        
        if mbrank >= 1 && mbrank <= 6 {
            
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    
    //处理转发,评论,赞的数量显示
    private func handleCountContent(count: Int, defaultTitle: String) -> String {
        
        if count > 0 {
            return "\(count)"
        } else {
            return defaultTitle
        }
    }
    
    //处理转发内容展示
    private func handleRetweetContent(status: JPStatusModel) {
        
        if status.retweeted_status != nil {
            //  获取转发微博的用户名
            let name = status.retweeted_status?.user?.screen_name
            let text = status.retweeted_status?.text
            
            if name != nil && text != nil {
                
                retweetContent = "@\(name!): \(text!)"
                
                retweetAttributeString = handleStatusAttributeString(text: retweetContent! ,isRetweet: true)
            }
        }
    }
    
    //  处理认证类型等级图片逻辑
    private func handleVerifiedTypeImage(verifiedType: Int) {
        //  认证类型等级 -1：没有认证，1，认证用户，2,3,5: 企业认证，220: 达人
        switch verifiedType {
        case 1:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
    }
    
    
}



